/**
 * Copyright (c) 2018, wuyy All rights reserved.
 * wuyy 专有/保密源代码,未经许可禁止任何人通过任何渠道使用、修改源代码.
 * QQ:16349023
 * 项目名称 : com.wy2.eclipse.tool.ui
 * @version V1.0
 */
package com.wy2.eclipse.tool.ui.wizard;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wy2.core.PropertiesDocument;
import com.wy2.core.common.EncodingConsts;
import com.wy2.core.tool.JsonTools;
import com.wy2.eclipse.tool.lib.ImportProject;
import com.wy2.eclipse.tool.lib.ImportProject.ImportProjectResult;
import com.wy2.eclipse.tool.lib.common.Constants;
import com.wy2.eclipse.tool.lib.entity.ProjectGenerateContext;
import com.wy2.eclipse.tool.lib.entity.ProjectInfo;
import com.wy2.eclipse.tool.lib.entity.ProjectModule;
import com.wy2.eclipse.tool.ui.UIActivator;
import com.wy2.eclipse.tool.ui.resource.Messages;
import com.wy2.generator.GenerateResult;
import com.wy2.generator.ProjectGenerator;
import com.wy2.generator.config.GeneratorConsts;

/**
 * 项目生成向导
 * @author wuyy<16349023@qq.com>
 * @date 2018年1月30日上午9:09:45
 * 
 */
public class ProjectGenerateWizard extends Wizard implements INewWizard {
    
    private static final Logger logger=LoggerFactory.getLogger(ProjectGenerateWizard.class);
    
    private IWorkbench workbench;
    private IStructuredSelection initSelection;
    
    private ProjectGenerateContext projectGenerateContext;
    
    private ProjectGenerateBasePage projectGenerateBasePage;

    public ProjectGenerateWizard() {
        setWindowTitle(Messages.getString("wy2.ProjectGenerateWizard.title"));
    }

    @Override
    public void addPages() {
        projectGenerateContext=new ProjectGenerateContext();
        projectGenerateBasePage = new ProjectGenerateBasePage(projectGenerateContext);
        addPage(projectGenerateBasePage);
    }

    @Override
    public boolean performFinish() {
        
        PropertiesDocument prop=new PropertiesDocument(true);
        File templateDirectory=new File(UIActivator.getDefault().getTemplateRootDirectory(), projectGenerateContext.getTemplate().getTemplateFolder());
        prop.setProperty(GeneratorConsts.GENERATOR_CONFIG_TEMPLATE_DIRECTORY, templateDirectory.getAbsolutePath());
        
//        File projectDirectory=new File(projectGenerateContext.getLocationPath(), projectGenerateContext.getArtifactId());
        File projectDirectory=new File(projectGenerateContext.getLocationPath());
        if(!projectDirectory.exists()) {
            projectDirectory.mkdirs();
        }
        prop.setProperty(GeneratorConsts.GENERATOR_CONFIG_OUTPUT_DIRECTORY, projectDirectory.getAbsolutePath());
        prop.setProperty(GeneratorConsts.GENERATOR_CONFIG_ENCODING,EncodingConsts.UTF_8);
        prop.setProperty(GeneratorConsts.GENERATOR_CONFIG_TEMPLATE_SUFFIX,GeneratorConsts.GENERATOR_CONFIG_TEMPLATE_SUFFIX_DEFAULT);
        ProjectGenerator projectGenerator=new ProjectGenerator(prop);
        
        
        
        Map<String,Object> model=new HashMap<>();
        model.put(GeneratorConsts.TEMPLATE_ATTRI_PROJECT_NAME,projectGenerateContext.getArtifactId());
        model.put(GeneratorConsts.TEMPLATE_ATTRI_GROUP_ID,projectGenerateContext.getGroupId());
        model.put(GeneratorConsts.TEMPLATE_ATTRI_ARTIFACT_ID,projectGenerateContext.getArtifactId());
        model.put(GeneratorConsts.TEMPLATE_ATTRI_BASEPACKAGE, projectGenerateContext.getPackages());
        model.put("version", projectGenerateContext.getVersion());
        try {
            LinkedList<GenerateResult> generateResults =projectGenerator.generate(model, true);
            logger.info("{}",projectGenerator.getOutputRootDirectory());
            generateResults.forEach(result->{
                logger.info("{} - {} - {} - {}",result.getMarker(), result.getSuccess(), result.getMarge(),result.getGenerateFilePath());
            });
            
            ProjectInfo projectInfo=JsonTools.load(new File(projectDirectory,projectGenerateContext.getArtifactId()+File.separator+Constants.GENERATE_PROJECT_INFO_FILE), EncodingConsts.UTF_8, ProjectInfo.class);
            if(projectInfo==null) {
                logger.error("创建项目 失败，原因是：{}","项目模板异常,缺少"+Constants.GENERATE_PROJECT_INFO_FILE);
                return false;
            }
            
            ImportProject importProject = new ImportProject();
            
            for (ProjectModule module : projectInfo.getModules()) {
                File projectFile=new File(projectDirectory,module.getName()+File.separator+ ".project");
                ImportProjectResult importResult=importProject.importProject(projectFile);
                if(importResult.getSuccess()) {
                    logger.info("导入项目 {} 成功",importResult.getProjectName());
                }else {
                    logger.error("导入项目 {} 否成功",importResult.getProjectName());
                }
            }
            
        }catch (Exception e) {
            logger.error("生成项目异常", e);
            return false;
        }
        
        
        return true;
    }

    /** 
     * @param workbench
     * @param selection 
     * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
     */
    @Override
    public void init(IWorkbench workbench, IStructuredSelection selection) {
        this.workbench=workbench;
        this.initSelection=selection;
        
    }

}
